package holdtime.xlxc.activities.practicedriving;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import holdtime.xlxc.R;
import holdtime.xlxc.bean.Time;
import holdtime.xlxc.model.QueryAddress;
import holdtime.xlxc.service.BLEService;
import holdtime.xlxc.tools.util.ActionBarUtil;
import holdtime.xlxc.tools.util.DateAndTimeUtil;
import holdtime.xlxc.tools.util.EmptyStringUtil;
import holdtime.xlxc.tools.util.ImageUtil;
import holdtime.xlxc.tools.util.ProgressHUDUtil;
import holdtime.xlxc.tools.util.SharedPreferencesUtil;
import holdtime.xlxc.tools.util.ToastUtil;

public class PracticeDrivingActivity extends ActionBarUtil {

    private static final String TAG = "XLXC";
    private static final int REQUEST_ENABLE_BT = 6;//请求打开蓝牙
    private static int LOCATION_CODE = 12;//请求定位
    Button beginBtn;//开始、结束按钮
    TextView stateTV;//状态
    ImageView banner;
    ImageView stateImg;
    TextView title;//请选择练习科目
    //    @Bind(R.id.item2)
//    Button subjectTwoBtn;//科目二按钮
//    @Bind(R.id.item3)
//    Button subjectThreeBtn;//科目三按钮
    ImageView clock_bk;//计时器背景
    ImageView clock_zz;//计时器指针
    TextView title1;//今日已学时间
    TextView timeTV;//计时器
    TextView lc;//今日已练里程
    ExpandableListView listView;
    private MyExpandableListAdapter myAdapter;//学员信息列表适配器
    private String sendStuID = "";//发送学员id
    //    private int subjectIndex = 0;//选择科目index
    private Time time;//计时练车model
    private Handler handlerA2;//a2handler
    private String sendA2Message;//发送a2消息
    private ProgressHUDUtil hud;
    private CountDownTimer t1Timer;
    private MyBroadCast mBroadCast;
    private boolean hasConnected = false;//是否连接成功过
    private boolean hasReceivedT1 = false;//连接上后判断是否会收到T1消息
    private boolean isFirstGetStudentID = true;
    private boolean hasLearned = false;//表示没有学习
    private boolean hasReceivedStuID = false;//是否收到过学员id
    //    private String param_a = "";//判断科目二、三按钮状态，UI用到
//    private String param_b = "";//判断科目二、三按钮状态，UI用到
    private Intent serviceIntent;
    private int a2Times = 0;
    //断开连接并返回上级页面,停止服务
    private boolean hasNotDisconnected = true;

//    Runnable mStatusCheckerA2 = new Runnable() {
//        @Override
//        public void run() {//每5秒发一次学员信息，收到回馈则停止，否则3次后断开返回
//            if (a2Times > 3) {
//                stopRepeatingTaskA2();
//                cutDownConnectAndBack();
//                Log.e(TAG, "a2发3次无应答断开连接");
//            } else {
//                send(sendA2Message);
//                Log.e(TAG, "发送学员信息");
//                a2Times++;
//                handlerA2.postDelayed(mStatusCheckerA2, 5000);
//            }
//        }
//    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "activity页面destroy");
        hud.dismissHUD();
//        isFirstGetStudentID = true;
        cutDownConnectAndBack();
        try {
            unregisterReceiver(mBroadCast);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.setActionBarTitle("计时练车");
        this.setHomeAsUpEnabled(true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_practice_driving);

        beginBtn = (Button) findViewById(R.id.begin);
        stateTV = (TextView) findViewById(R.id.state);
        banner = (ImageView) findViewById(R.id.banner);
        stateImg = (ImageView) findViewById(R.id.state_img);
        title = (TextView) findViewById(R.id.title);
        clock_bk = (ImageView) findViewById(R.id.clock_bk);
        clock_zz = (ImageView) findViewById(R.id.clock_zz);
        title1 = (TextView) findViewById(R.id.title1);
        timeTV = (TextView) findViewById(R.id.timeTV);
        lc = (TextView) findViewById(R.id.lc);
        listView = (ExpandableListView) findViewById(R.id.info_listview);

        banner.setImageBitmap(ImageUtil.streamBitmap(this, R.drawable.counttime_banner));
        clock_bk.setImageBitmap(ImageUtil.streamBitmap(this, R.drawable.clock_bk));
        clock_zz.setImageBitmap(ImageUtil.streamBitmap(this, R.drawable.clock_zz));

        time = new Time();
        handlerA2 = new Handler();

        stateView(0);//未连接显示页面
//        hideDefaultView(false);
        hideCountView(true);
        beginBtn.setBackgroundResource(R.drawable.stop);
        beginBtn.setEnabled(false);
//        beginBtn.setVisibility(View.INVISIBLE);

        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            ToastUtil.showToast(this, "蓝牙不可用");
            this.finish();
        }
        serviceIntent = new Intent(PracticeDrivingActivity.this, BLEService.class);

        title.setText(getIntent().getStringExtra("pxxm"));
        title1.setText("今日已学时间");
        timeTV.setText("00：00：00");
        lc.setText("今日已练里程");

        assert mBluetoothAdapter != null;
        if (!mBluetoothAdapter.isEnabled()) {//打开蓝牙开关
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            if (IsConnected.getCurrent().hasConnected) {
                Log.e(TAG, "已连接 直接注册广播");
//                stateView(2);//未连接显示页面
//                hideDefaultView(true);
//                hideCountView(false);
//                beginBtn.setBackgroundResource(R.drawable.stop);
//                beginBtn.setEnabled(true);
//                beginBtn.setVisibility(View.VISIBLE);
                mBroadCast = new MyBroadCast();
                initReceiver();//注册广播
//                queryStudentInfo();
//                hasConnected = true;//是否连接成功过
//                hasReceivedT1 = true;//连接上后判断是否会收到T1消息
//                isFirstGetStudentID = false;
//                hasLearned = true;//表示没有学习
//                hasReceivedStuID = true;//是否收到过学员id
//                hasDisconnected = false;
//                isUploadingStuInfo = false;
            } else {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)//定位权限
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
                } else {
                    connectWithQRCode();//连接二维码
                }
            }
        }
        hud = new ProgressHUDUtil(this);
        hud.showHUD();

        beginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                learn(false);
                beginBtn.setVisibility(View.INVISIBLE);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == LOCATION_CODE) {
            connectWithQRCode();
        } //定位成功
    }

//    private void queryStudentInfo() {
//        String url = "http://123.56.85.108:8090/jpms2/business/interface/getLessonSummaryByApp/" + UserPersistUtil.info(this, "num");
//        RequestQueue requestQueue = Volley.newRequestQueue(getBaseContext());
//        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        try {//
//                            String result = response.substring(1, response.length() - 1).replace("\\", "");
//                            JSONObject jo1 = new JSONObject(result);
//                            String resultCode = jo1.getString("ResultCode");
//                            if (resultCode.equals("0")) {
//                                Gson gson = new Gson();
//                                time = gson.fromJson(jo1.getJSONArray("Record").get(0).toString(), Time.class);
//                                initData();
//                                initView();
//                                initEvents();
//                            }
//                        } catch (JSONException e) {
//                            ToastUtil.showToast(getBaseContext(), "加载失败，请返回重新扫码");
//                            cutDownConnectAndBack();
//                            Log.e(TAG, "加载失败，请返回重新扫码");
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                ToastUtil.showToast(getBaseContext(), "加载失败，请返回重新扫码");
//                cutDownConnectAndBack();
//                Log.e(TAG, "加载失败，请返回重新扫码");
//            }
//        });
//        stringRequest.setRetryPolicy(new DefaultRetryPolicy(getResources().getInteger(R.integer.defaultRequestTimeOut), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//        requestQueue.add(stringRequest);
//    }

    private void initReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(AppConstants.MYACTION);
        registerReceiver(mBroadCast, filter);
    }

    private void send(String s) {//发送消息
        Intent intent = new Intent();
        intent.setAction(AppConstants.SERVICE_BROAD_ACTION);
        intent.putExtra("send", s);
        sendBroadcast(intent);
        Log.e(TAG, "发送数据");
    }

//    private void startRepeatingTaskA2() {
//        mStatusCheckerA2.run();
//    }
//
//    private void stopRepeatingTaskA2() {
//        handlerA2.removeCallbacks(mStatusCheckerA2);
//    }

    //开始按钮点击调用方法
    private void learn(boolean ifBegin) {
        try {
            JSONObject jo = new JSONObject();
//            SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.CHINA);
//            String date = sDateFormat.format(new Date());
//            jo.put("time", date);
            jo.put("mt", "A1");
//            if (subjectIndex == 2) {//科目二
                jo.put("p2", getIntent().getStringExtra("pxbfCode"));
//                Log.e(TAG, "选择科目二");
//            } else if (subjectIndex == 3) {//科目三
//                jo.put("p2", "3");
//                Log.e(TAG, "选择科目三");
//            }
//            if (ifBegin) {//开始学习
//                jo.put("p1", "1");
//                Log.e(TAG, "发送开始学习指令");
//            } else {//停止学习
                jo.put("p1", "0");
                Log.e(TAG, "发送停止学习指令");
//                beginBtn.setEnabled(false);
//            }
            send(jo.toString());//发送A1
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_ENABLE_BT://请求打开蓝牙
                if (IsConnected.getCurrent().hasConnected) {
                    mBroadCast = new MyBroadCast();
                    initReceiver();//注册广播
                } else {
                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)//定位,oncreate里此方法，如果用户选择打开蓝牙，则不调用，此处调用
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
                    } else {
                        connectWithQRCode();
                    }
                }
//                hideDefaultView(false);
                hideCountView(true);
                stateView(0);
                beginBtn.setEnabled(false);
                beginBtn.setBackgroundResource(R.drawable.stop);
                break;
        }
    }

    //状态显示
    private void stateView(int index) {
        switch (index) {
            case 0:
                stateTV.setText("未连接");
                stateImg.setImageBitmap(ImageUtil.streamBitmap(this, R.drawable.disconnect));
                break;
//            case 1:
//                stateTV.setText("正在连接");
//                stateImg.setImageBitmap(ImageUtil.streamBitmap(getBaseContext(), R.drawable.connecting));
//                break;
            case 2:
                stateTV.setText("已连接");
                stateImg.setImageBitmap(ImageUtil.streamBitmap(this, R.drawable.connected));
                break;
        }
    }

    private void cutDownConnectAndBack() {
        if (hasNotDisconnected) {
            hasNotDisconnected = false;
            Log.e(TAG, "断开连接返回上级");

            IsConnected.getCurrent().hasConnected = false;
            try {
                unregisterReceiver(mBroadCast);
            } catch (Exception e) {
                e.printStackTrace();
            }
            stopService(serviceIntent);
            Log.e(TAG, "蓝牙Service停止");
            ToastUtil.showToast(PracticeDrivingActivity.this, "连接已断开");
            SystemClock.sleep(1000);
            finish();
        }
    }

    //选择科目按钮效果
//    private void subjectBtnState(boolean isSubjectTwo) {
//        if (isSubjectTwo) {
//            subjectTwoBtn.setBackgroundColor(Color.rgb(251, 124, 70));
//            subjectThreeBtn.setBackgroundColor(Color.rgb(255, 255, 255));
//            subjectTwoBtn.setTextColor(Color.rgb(255, 255, 255));
//            subjectThreeBtn.setTextColor(Color.rgb(0, 0, 0));
//        } else {
//            subjectThreeBtn.setBackgroundColor(Color.rgb(251, 124, 70));
//            subjectTwoBtn.setBackgroundColor(Color.rgb(255, 255, 255));
//            subjectTwoBtn.setTextColor(Color.rgb(0, 0, 0));
//            subjectThreeBtn.setTextColor(Color.rgb(255, 255, 255));
//        }
//    }

    //隐藏选择页面
//    private void hideDefaultView(boolean isHide) {
//        if (isHide) {
//            title.setVisibility(View.INVISIBLE);
////            subjectTwoBtn.setVisibility(View.INVISIBLE);
////            subjectThreeBtn.setVisibility(View.INVISIBLE);
//        } else {
//            title.seXXtVisibility(View.VISIBLE);
////            subjectTwoBtn.setVisibility(View.VISIBLE);
////            subjectThreeBtn.setVisibility(View.VISIBLE);
//        }
//    }

    //隐藏计时页面
    private void hideCountView(boolean isHide) {
        if (isHide) {
            clock_bk.setVisibility(View.INVISIBLE);
            clock_zz.setVisibility(View.INVISIBLE);
//            title1.setVisibility(View.INVISIBLE);
            timeTV.setVisibility(View.INVISIBLE);
            lc.setVisibility(View.INVISIBLE);
        } else {
            clock_bk.setVisibility(View.VISIBLE);
            clock_zz.setVisibility(View.VISIBLE);
//            title1.setVisibility(View.VISIBLE);
            timeTV.setVisibility(View.VISIBLE);
            lc.setVisibility(View.VISIBLE);
        }
    }

    private void connectWithQRCode() {//二维码扫描
        Log.e(TAG, "二维码扫描");
        String qrCode = getIntent().getStringExtra("result");
        if (qrCode != null) {
            qrCode = qrCode.replaceAll("start<", "");
            qrCode = qrCode.replaceAll(">end", "");
            BLEService.bluetoothName = qrCode.split(":")[0];
            startService(serviceIntent);
            SystemClock.sleep(1000);
            mBroadCast = new MyBroadCast();
            initReceiver();//注册广播
        }
    }

    private void initData() {//学车信息listview
        List<String> groupData = new ArrayList<>();
        groupData.add("练车信息");
        List<ChildItem> childItems = new ArrayList<>();
        ChildItem childData1 = new ChildItem("姓名", time.getName());
        childItems.add(childData1);
        ChildItem childData2 = new ChildItem("身份证号码", (String) SharedPreferencesUtil.get(this, "num", ""));
        childItems.add(childData2);
        ChildItem childData3 = new ChildItem("科目二学时", "总学习：" + time.getScLearnTime2() + "学时");
        childItems.add(childData3);
        ChildItem childData4 = new ChildItem("科目二里程", "总学习：" + time.getK2Xslcs() + "km");
        childItems.add(childData4);
        ChildItem childData5 = new ChildItem("科目三学时", "总学习：" + time.getScLearnTime3() + "学时");
        childItems.add(childData5);
        ChildItem childData6 = new ChildItem("科目三里程", "总学习：" + time.getK3Xslcs() + "km");
        childItems.add(childData6);
        Map<Integer, List<ChildItem>> childData = new HashMap<>();
        childData.put(0, childItems);
        myAdapter = new MyExpandableListAdapter(getBaseContext(), groupData, childData);
    }

    private void initView() {
        listView.setGroupIndicator(null);
        listView.setAdapter(myAdapter);
        myAdapter.notifyDataSetChanged();
        registerForContextMenu(listView);
    }

    private void initEvents() {
        listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                return true;
            }
        });
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }

    private class MyBroadCast extends BroadcastReceiver {//接收一切终端消息

        @Override
        public void onReceive(Context context, Intent intent) {
            String msg = intent.getStringExtra("mTxtRead");
            if (msg != null) {
                hud.dismissHUD();
                try {
                    final JSONObject jo = new JSONObject(msg);
//                    Log.e(TAG, "T1" + jo.toString());
                    if (jo.getString("mt").equals("A1")) {//请求开始、结束学习
                        Log.e(TAG, "收到A1");
                    } else if (jo.getString("mt").equals("A2")) {//学员信息传输
                        if (!hasReceivedStuID) {
//                            stopRepeatingTaskA2();//停止a2handler
                            Log.e(TAG, "收到A2");
                            beginBtn.setEnabled(true);
                            hasReceivedStuID = true;
//                            beginBtn.setVisibility(View.VISIBLE);
                        }
                    } else if (jo.getString("mt").equals("T1")) {//终端发出报文
                        beginBtn.setEnabled(true);
                        stateView(2);//连接成功页面
                        hasReceivedT1 = true;//收到T1消息
                        if (isFirstGetStudentID) {//第一次连接
                            isFirstGetStudentID = false;
//                            QueryAddress managerService = new QueryAddress();
                            if (EmptyStringUtil.ifNotEmpty((String) SharedPreferencesUtil.get(PracticeDrivingActivity.this, "num", ""))) {
                                QueryAddress address = new QueryAddress();
                                String url = address.studentInfo((String) SharedPreferencesUtil.get(PracticeDrivingActivity.this, "add", ""), (String) SharedPreferencesUtil.get(PracticeDrivingActivity.this, "num", ""));
                                //                                if (isBameng) {
//                                    url = managerService.studentInfoBM(UserPersistUtil.info(getBaseContext(), "num"));
//                                } else {
//                                    url = managerService.studentInfo(UserPersistUtil.info(getBaseContext(), "num"));
//                                }
                                RequestQueue requestQueue = Volley.newRequestQueue(getBaseContext());
                                StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                                        new Response.Listener<String>() {
                                            @Override
                                            public void onResponse(String response) {
                                                try {
//                                                    String result = response.substring(1, response.length() - 1).replace("\\", "");
                                                    JSONObject jo1 = new JSONObject(response);
                                                    String resultCode = jo1.getString("resultCode");
                                                    if (resultCode.equals("0")) {
                                                        Gson gson = new Gson();
                                                        time = gson.fromJson(jo1.getJSONObject("record").toString(), Time.class);
                                                        String appStudentid = time.getStunum();
                                                        Log.e(TAG, "获取学员信息成功" + time.getName());
                                                        String zdStudentid = jo.getString("p12");

                                                        //传输学员信息
                                                        JSONObject studentInfoJO = new JSONObject();
//                                                        studentInfoJO.put("time", DateAndTimeUtil.currentDateAndTime());
                                                        studentInfoJO.put("mt", "A2");
                                                        studentInfoJO.put("p1", time.getStunum());//学员id
                                                        studentInfoJO.put("p2", time.getName());//学员姓名
                                                        studentInfoJO.put("p3", time.getPersonNum());//身份id
                                                        studentInfoJO.put("p4", getIntent().getStringExtra("kcbmCode"));//学校id
                                                        studentInfoJO.put("p5", getIntent().getStringExtra("classId"));//准驾类型
//                                                        studentInfoJO.put("param6", "0");//发卡次数，0表示无卡
//                                                        studentInfoJO.put("param7", time.getScLearnTime2());//科目2总学习时间 单位小时
//                                                        studentInfoJO.put("param8", time.getK2Xslcs());//科目2总学习里程 单位米
//                                                        studentInfoJO.put("param9", time.getScLearnTime3());//科目3总学习时间 单位小时
//                                                        studentInfoJO.put("param10", time.getK3Xslcs());//科目3总学习里程 单位米

                                                        if (zdStudentid == null) {//终端没有学员信息则上传
                                                            //上传学员信息
                                                            sendStuID = time.getStunum();
                                                            sendA2Message = studentInfoJO.toString();
                                                            SystemClock.sleep(1000);
//                                                            startRepeatingTaskA2();
                                                            send(sendA2Message);
                                                            hud.showHUD();
                                                            //学车信息listview
                                                            initData();
                                                            initView();
                                                            initEvents();
                                                            Log.e(TAG, "上传学员信息");
                                                        } else if (appStudentid.equals(zdStudentid)) {//学员信息一致
                                                            //不操作
                                                        } else {//学员信息不一致
//                                                            if (jo.getString("p10").equals("2")) {//停止学习
//                                                                subjectIndex = 2;
//                                                                learn(false);
//                                                            } else if (jo.getString("p10").equals("3")) {
//                                                                subjectIndex = 3;
//                                                                learn(false);
//                                                            }
                                                            //上传学员信息
                                                            sendStuID = time.getStunum();
                                                            sendA2Message = studentInfoJO.toString();
                                                            SystemClock.sleep(1000);
//                                                            startRepeatingTaskA2();
                                                            send(sendA2Message);
//                                                            hud.showHUD();
                                                            //学车信息listview
                                                            initData();
                                                            initView();
                                                            initEvents();
                                                            Log.e(TAG, "上传学员信息");
                                                        }
                                                    } else {
                                                        ToastUtil.showToast(getBaseContext(), "非学员不能练车");
                                                        cutDownConnectAndBack();
                                                    }
                                                } catch (JSONException e) {
                                                    ToastUtil.showToast(getBaseContext(), "加载失败，请返回重新扫码");
                                                    cutDownConnectAndBack();
                                                    Log.e(TAG, "加载失败，请返回重新扫码");
                                                    e.printStackTrace();
                                                }
                                            }
                                        }, new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError error) {
                                        ToastUtil.showToast(getBaseContext(), "加载失败，请返回重新扫码");
                                        cutDownConnectAndBack();
                                        Log.e(TAG, "加载失败，请返回重新扫码");
                                    }
                                });
                                stringRequest.setRetryPolicy(new DefaultRetryPolicy(getResources().getInteger(R.integer.defaultRequestTimeOut), DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                                requestQueue.add(stringRequest);
                            }
                        }

                        //参数12，表示是否收到学员信息
                        String studentID = jo.getString("p12");
                        if (studentID != null && studentID.equals(sendStuID) && !hasReceivedStuID) {
//                            stopRepeatingTaskA2();
                            hud.dismissHUD();
                            Log.e(TAG, "收到终端回传学员ID");
                            beginBtn.setEnabled(true);
                            hasReceivedStuID = true;
//                            beginBtn.setVisibility(View.VISIBLE);
                        }

                        //参数9，学习状态，1在学习，0没学习，2暂停中
                        if (jo.has("p9")) {
                            String status = jo.getString("p9");
                            if (hasLearned && status.equals("0")) {//正在学习，突然断开
                                cutDownConnectAndBack();
                                Log.e(TAG, "正在学习、突然断开");
                            } else if (status.equals("0")) {//没有学习，可能尚未定位
//                                hideDefaultView(false);
                                hideCountView(true);
//                                beginBtn.setBackgroundResource(R.drawable.start);
                            } else if (status.equals("1")) {//正在学习
//                                Log.e(TAG, "正在学习");
                                beginBtn.setEnabled(true);
//                                if (jo.getString("p10").equals("2")) {//学习科目二
//                                    subjectBtnState(true);
//                                } else if (jo.getString("p10").equals("3")) {//学习科目三
//                                    subjectBtnState(false);
//                                }
                                stateView(2);
//                                hideDefaultView(true);
                                hideCountView(false);
                                hasLearned = true;
                                beginBtn.setBackgroundResource(R.drawable.stop);
//                                subjectTwoBtn.setEnabled(false);
//                                subjectThreeBtn.setEnabled(false);
                                lc.setText("今日已练里程" + String.valueOf(Integer.parseInt(jo.getString("p17")) / 1000) + "km");
                                timeTV.setText(DateAndTimeUtil.convertSecondToTime(Integer.valueOf(jo.getString("p15"))));
                                clock_zz.setImageBitmap(ImageUtil.turnImage(ImageUtil.streamBitmap(getBaseContext(), R.drawable.clock_zz), (Integer.valueOf(jo.getString("p15")) * 180 / 14400)));
                            } else {//停止学习
                                hasLearned = false;
//                                beginBtn.setBackgroundResource(R.drawable.start);
//                                subjectTwoBtn.setEnabled(true);
//                                subjectThreeBtn.setEnabled(true);
                                cutDownConnectAndBack();
                                Log.e(TAG, "停止学习");
                            }
//                            String btn_index = jo.getString("p10");//参数10表示学习科目，获取该参数为了展示科目按钮被选择状态
//                            if (param_b.equals("")) {
//                                param_b = btn_index;
//                                if (param_b.equals("2")) {
//                                    subjectIndex = 2;
//                                } else if (param_b.equals("3")) {
//                                    subjectIndex = 3;
//                                }
//                            } else {
//                                if (!param_b.equals(btn_index)) {
//                                    param_b = btn_index;
//                                    if (param_b.equals("2")) {
//                                        subjectIndex = 2;
//                                    } else if (param_b.equals("3")) {
//                                        subjectIndex = 3;
//                                    }
//                                }
//                            }
//                            if (param_a.equals("")) {
//                                param_a = status;
//                                if (param_a.equals("1")) {
//                                    hasLearned = true;
//                                    beginBtn.setBackgroundResource(R.drawable.stop);
//                                    subjectTwoBtn.setEnabled(false);
//                                    subjectThreeBtn.setEnabled(false);
//                                } else if (param_a.equals("0") || param_a.equals("2")) {
//                                    hasLearned = false;
//                                    beginBtn.setBackgroundResource(R.drawable.start);
//                                    subjectTwoBtn.setEnabled(true);
//                                    subjectThreeBtn.setEnabled(true);
//                                }
//                            } else {
//                                if (!param_a.equals(status)) {
//                                    param_a = status;
//                                    if (param_a.equals("1")) {
//                                        hasLearned = true;
//                                        beginBtn.setBackgroundResource(R.drawable.stop);
//                                        subjectTwoBtn.setEnabled(false);
//                                        subjectThreeBtn.setEnabled(false);
//                                    } else if (param_a.equals("0") || param_a.equals("2")) {
//                                        hasLearned = false;
//                                        beginBtn.setBackgroundResource(R.drawable.start);
//                                        subjectTwoBtn.setEnabled(true);
//                                        subjectThreeBtn.setEnabled(true);
//                                    }
//                                }
//                            }
                        }
                    } else if (jo.getString("mt").equals("T2")) {//终端发出报文
                        ToastUtil.showToast(PracticeDrivingActivity.this, "学习停止");
                        cutDownConnectAndBack();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            //连接状态
            String state = intent.getStringExtra("mTxtStatus");
            if (state != null && state.equals("连接成功")) {
                hasConnected = true;
                hud.dismissHUD();
//                hideDefaultView(false);
                hideCountView(true);
                stateView(2);//已连接状态
                listView.setVisibility(View.VISIBLE);
                t1Timer = new CountDownTimer(30000, 1000) {//30秒没收到t1，则断开连接返回
                    @Override
                    public void onTick(long l) {
                    }

                    @Override
                    public void onFinish() {
                        if (!hasReceivedT1) {
                            cutDownConnectAndBack();
                            Log.e(TAG, "30秒没收到t1");
                        } else {
                            t1Timer = null;
                        }
                    }
                }.start();
            } else if (state != null && state.equals("未扫描到设备")) {
                hud.dismissHUD();
                cutDownConnectAndBack();
                Log.e(TAG, "未扫描到设备");
            } else if (state != null) {
                hud.dismissHUD();
                stateView(0);
//                hideDefaultView(false);
                hideCountView(true);
                SystemClock.sleep(1000);
                if (hasConnected) {
                    cutDownConnectAndBack();
                }
            }
        }
    }
}
